import React, { useState, useEffect } from 'react';
import { Card, Breadcrumb, Button, Form, message, Tabs } from 'antd';
import FormShow from './components/formShow';
import ActClassify from './components/actClassify';
import styles from './index.less';
import { Link, history } from 'umi';
const { TabPane } = Tabs;
import dayjs from 'dayjs';
import { saveDraftsApi, editActivityApi, getRegionApi } from '@/api/activity';

export default function CreateAct({
  history: {
    location: { state },
  },
}) {
  const [changeForm] = Form.useForm();
  const [applyForm] = Form.useForm();
  const [voteForm] = Form.useForm();
  const [flag, setFlag] = useState('1');
  const [isSignUp, setIsSignUp] = useState()
  const [isVote, setIsVote] = useState()
  const [regionLists, setRegionLists] = useState([]);
  const [requiredEntryForms, setRequiredEntryForms] = useState([]);
  const [voteWay, setVoteWay] = useState()
  /** 地区二级懒加载 */
  const loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const {
      data: { data },
    } = await getRegionApi({
      parentId: targetOption.addressCode,
      addressLevel: 2,
    });

    targetOption.loading = false;
    targetOption.children = [...data];
    setRegionLists([...regionLists]);
  };

  /** 回填操作 */
  const backfill = async () => {
    /** 获取地区 */
    const one = await getRegionApi({ addressLevel: 1 });
    const newData = one.data.data.map((item) => {
      item.isLeaf = false;
      return item;
    });
    setRegionLists([...newData]);

    if (!state) return;
    const {
      data: { data },
    } = await editActivityApi(state);
    setIsSignUp(data.isSignUp)
    setIsVote(data.isVote)

    /** 地区 */
    const Index = newData.findIndex(
      (item) => item.addressCode == data.provinceCode,
    );
    const city = await getRegionApi({
      parentId: data.provinceCode,
      addressLevel: 2,
    });
    const item = city.data.data.find(
      (item) => item.addressCode == data.cityCode,
    );
    newData[Index].children = [item];
    setRegionLists([...newData]);
    /** 日程对象 */
    const scheduleVOS = data.scheduleVOS.map((item) => {
      return {
        scheduleName: item.scheduleName,
        scheduleDate: dayjs(item.scheduleDate),
      };
    });
    const index1 = data.activityVOS.findIndex(item => item.activityType == 1)
    const index2 = data.activityVOS.findIndex(item => item.activityType == 2)
    /** 第二个表单的Tags选中 */
    const tag = JSON.parse(data.activityVOS[index1].requiredEntryForm)
    const b = tag.map((item) => {
      return item.key
    })

    setRequiredEntryForms(b)
    /** 不补充项目名称 */
    let optionalEntryForms
    if(data.activityVOS[index1].optionalEntryForms){
        optionalEntryForms = data.activityVOS[index1].optionalEntryForms.map(item => {
        return {
          key: item?.key
        }
      })
    }

    /** 下拉 */
    setVoteWay(data.activityVOS[index2].voteWay)
    /** 第三个表单回填数据处理 */
    const voteObject = data.activityVOS[index2].voteObjectVOS.slice(1).map(item => {
      return {
        instructions: item.instructions,
        picturePic: [{uid: '-4', name: item.pictureKey, url: item.pictureUrl}],
        name: item.name
      }
    })
    changeForm.setFieldsValue({
      activityName: data.activityName,
      activityTime: [dayjs(data.startDate), dayjs(data.endDate)],
      Province: [data.provinceCode, data.cityCode],
      activitySite: data.activitySite,
      activityContent: data.activityContent,
      activityOrganizers: data.activityOrganizers,
      pictureUrl: [{ uid: '-1', name: data.pictureKey, url: data.pictureUrl }],
      thumbnailPictureUrl: [
        {
          uid: '-2',
          name: data.thumbnailPictureKey,
          url: data.thumbnailPictureUrl,
        },
      ],
      scheduleVOS: scheduleVOS,
    });
    applyForm.setFieldsValue({
      numberLimit: data.activityVOS[index1].numberLimit,
      activityTime: [
        dayjs(data.activityVOS[index1].startDate),
        dayjs(data.activityVOS[index1].endDate)
      ],
      optionalEntryForms
    })
    voteForm.setFieldsValue({
      activityTime:[
        dayjs(data.activityVOS[index2].startDate),
        dayjs(data.activityVOS[index2].endDate)
      ],
      voteWay: data.activityVOS[index2].voteWay,
      dayVoteLimit: data.activityVOS[index2].dayVoteLimit,
      singlePlayerLimit: data.activityVOS[index2].singlePlayerLimit,
      instructions: data.activityVOS[index2].voteObjectVOS[0].instructions,
      name: data.activityVOS[index2].voteObjectVOS[0].name,
      picturePic: [
        {
          uid: '-3',
          name: data.activityVOS[index2].voteObjectVOS[0].pictureKey,
          url: data.activityVOS[index2].voteObjectVOS[0].pictureUrl
        }
      ],
      voteObjectVOS: [...voteObject]
    })
  };
  useEffect(() => {
    backfill();
  }, []);


  /** 下一步 */
  const nextHandler = async () => {
    const res = await changeForm
      .validateFields()
      .catch(() => message.error('表单验证不通过'));
    if (!(res instanceof Object)) return;
    setFlag('2');
  };

  /** 上一步 */
  const prevHandler = async () => {
    setFlag('1');
  };

  /** 用于接收子组件传递过来的tags数组 第二个表单 */
  const getTags = (values) => {
    setRequiredEntryForms([...values]);
  };
  /** 保存草稿 */
  const saveDrafts = async () => {
    const res = await changeForm
      .validateFields()
      .catch(() => message.error('表单验证不通过'));
    const res1 = await applyForm
      .validateFields()
      .catch(() => message.error('表单验证不通过'));
    const res2 = await voteForm
      .validateFields()
      .catch(() => message.error('表单验证失败'));
      if(Object.keys(res).length && Object.keys(res1).length && Object.keys(res1).length){
        /** 日程对象时间处理 */
        const scheduleVOS = res.scheduleVOS.map((item) => {
          item.scheduleDate = dayjs(item.scheduleDate).format(
            'YYYY-MM-DD HH:mm:ss',
          );
          return item;
        });

        /** 处理第二个表单数组 */
        const prev1 = requiredEntryForms.reduce((prev, curr) => {
          prev.push({ key: curr });
          return prev;
        }, []);

        /** 处理第三个表单的图片 */
        const voteObjectVOS = res2.voteObjectVOS.reduce((prev, curr) => {
          prev.push({
            name: curr.name,
            instructions: curr.instructions,
            pictureKey: curr.picturePic[0].name,
            pictureUrl: curr.picturePic[0].url,
          });
          return prev;
        }, []);

        const obj = {
          activityName: res.activityName,
          activitySite: res.activitySite,
          activityContent: res.activityContent,
          activityOrganizers: res.activityOrganizers,
          startDate: dayjs(res.activityTime[0]).format('YYYY-MM-DD HH:mm:ss'),
          endDate: dayjs(res.activityTime[1]).format('YYYY-MM-DD HH:mm:ss'),
          provinceCode: res.Province[0],
          cityCode: res.Province[1],
          pictureKey: res.pictureUrl[0].name,
          pictureUrl: res.pictureUrl[0].url,
          thumbnailPictureKey: res.thumbnailPictureUrl[0].name,
          thumbnailPictureUrl: res.thumbnailPictureUrl[0].url,
          scheduleVOS,
          isVote: 1,
          isSignUp: 1,
          isSignIn: 0,
          isRobTickets: 0,
          isLuckyDraw: 0,
          activityVOS: [
            {
              activityType: 1,
              startDate: dayjs(res1.activityTime[0]).format('YYYY-MM-DD HH:mm:ss'),
              endDate: dayjs(res1.activityTime[1]).format('YYYY-MM-DD HH:mm:ss'),
              numberLimit: res1.numberLimit,
              requiredEntryForms: prev1,
              optionalEntryForms: [...res1.optionalEntryForms],
            },
            {
              activityType: 2,
              startDate: dayjs(res2.activityTime[0]).format('YYYY-MM-DD HH:mm:ss'),
              endDate: dayjs(res2.activityTime[1]).format('YYYY-MM-DD HH:mm:ss'),
              voteWay: res2.voteWay,
              dayVoteLimit: res2.dayVoteLimit,
              singlePlayerLimit: res2.singlePlayerLimit,
              voteObjectVOS: [
                {
                  instructions: res2.instructions,
                  pictureKey: res2.picturePic[0].name,
                  pictureUrl: res2.picturePic[0].url,
                  name: res2.name,
                },
                ...voteObjectVOS,
              ],
            },
          ],
        };
        if (!state){
          /** 保存草稿的请求 */
          const save = await saveDraftsApi(obj);
          if (save.data.code != 200) return message.error(save.data.message);
          message.success('保存成功');
        }else{
          /** 修改草稿 */
          const save1 = await saveDraftsApi({...state, ...obj})
          if (save1.data.code != 200) return message.error(save1.data.message);
          message.success('修改成功');
        }
        history.push('/');
    }else{
      message.info('请再次验证表单')
    }
  };
  return (
    <div>
      {/** 面包屑导航 */}
      <div className={styles.bread}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/createActivity">创建活动</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Link to="/changeAct">添加</Link>
          </Breadcrumb.Item>
        </Breadcrumb>
        <h1>添加</h1>
      </div>
      {/* 卡片区域 */}
      <div style={{ padding: '0 20px' }}>
        <Card style={{ padding: '0px 15px' }}>
          <Tabs activeKey={flag}
              defaultActiveKey="1"
          >
            <TabPane key="1"
                tab="基本信息"
            >
              <FormShow
                  changeForm={changeForm}
                  loadData={loadData}
                  regionLists={regionLists}
              />
            </TabPane>
            <TabPane forceRender
                key="2"
                tab="活动信息"
            >
              <ActClassify
                  applyForm={applyForm}
                  getTags={getTags}
                  isSignUp1={isSignUp}
                  isVote1={isVote}
                  requiredEntryForms={requiredEntryForms}
                  voteForm={voteForm}
                  voteWay={voteWay}
              />
            </TabPane>
          </Tabs>

          {/* 按钮区域 */}

          {flag == 1 ? (
            <div className={styles.btnBox}>
              <Button
                  className={styles.btn}
                  onClick={nextHandler}
                  type="primary"
              >
                下一步
              </Button>
              <Button className={styles.btn}
                  onClick={saveDrafts}
              >
                保存草稿
              </Button>
              <Button className={styles.btn}>
                预览
              </Button>
            </div>
          ) : (
            <div className={styles.btnBox}>
              <Button
                  className={styles.btn}
                  onClick={prevHandler}
                  type="primary"
              >
                上一步
              </Button>
              <Button className={styles.btn}
                  onClick={saveDrafts}
              >
                保存草稿
              </Button>
              <Button className={styles.btn}>
                预览
              </Button>
              <Button className={styles.btn}>发布</Button>
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}
